package edu.univercidade.tcc.server.validator;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Collection;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;

import edu.univercidade.tcc.server.model.Membership;
import edu.univercidade.tcc.server.model.ProjectRole;

@Target({ TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = MembershipMustHaveRole.Validator.class)
@Documented
public @interface MembershipMustHaveRole {
	String message() default "Os membros de um projeto devem ter ao menos um papel no projeto.";

	Class<?>[] groups() default {};

	Class<? extends Payload>[] payload() default {};

	class Validator implements
			ConstraintValidator<MembershipMustHaveRole, Object> {

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * javax.validation.ConstraintValidator#initialize(java.lang.annotation
		 * .Annotation)
		 */
		@Override
		public void initialize(MembershipMustHaveRole arg0) {

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see javax.validation.ConstraintValidator#isValid(java.lang.Object,
		 * javax.validation.ConstraintValidatorContext)
		 */
		@Override
		public boolean isValid(Object target, ConstraintValidatorContext context) {
			Collection<ProjectRole> roles = ((Membership) target).getRoles();
			return roles != null && !roles.isEmpty();
		}

	}
}
